// 监听快捷键命令
chrome.commands.onCommand.addListener(async (command) => {
  if (command === 'add-article') {
    // 获取当前活动标签页
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    if (!tab) return;
    
    // 检查是否是微信文章页面
    if (!tab.url || !tab.url.includes('mp.weixin.qq.com')) {
      // 注入脚本显示错误提示
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: showToast,
        args: ['请在微信公众号文章页面使用此功能', 'error']
      });
      return;
    }
    
    // 注入内容脚本提取数据
    try {
      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: extractArticleData
      });
      
      if (results && results[0] && results[0].result) {
        const articleData = results[0].result;
        
        // 保存文章
        const saveResult = await saveArticle(articleData);
        
        // 显示结果提示
        await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          func: showToast,
          args: [saveResult.message, saveResult.type]
        });
      }
    } catch (error) {
      console.error('提取文章数据失败:', error);
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: showToast,
        args: ['提取文章数据失败', 'error']
      });
    }
  }
});

// 提取文章数据的函数（将被注入到页面中执行）
function extractArticleData() {
  // 提取标题
  const titleEl = document.querySelector('#activity-name');
  const titleMeta = document.querySelector('meta[property="og:title"]');
  const title = titleEl?.textContent?.trim() || titleMeta?.content?.trim() || '';
  
  // 提取公众号名称
  const authorEl = document.querySelector('#js_name');
  const authorMeta = document.querySelector('meta[property="og:article:author"]');
  const author = authorEl?.textContent?.trim() || authorMeta?.content?.trim() || '';
  
  // 提取发布时间
  const timeEl = document.querySelector('#publish_time');
  const timeMeta = document.querySelector('meta[property="article:published_time"]');
  const publishTime = timeEl?.textContent?.trim() || timeMeta?.content?.trim() || '';
  
  // 获取链接
  const url = window.location.href;
  
  return {
    title,
    author,
    publishTime,
    url
  };
}

// 保存文章到本地存储
async function saveArticle(articleData) {
  try {
    const { articles = [] } = await chrome.storage.local.get('articles');
    
    // 检查是否重复（基于URL）
    // 清理URL，移除查询参数进行比较
    const cleanUrl = (url) => {
      try {
        const urlObj = new URL(url);
        // 保留核心路径，移除一些追踪参数
        return urlObj.origin + urlObj.pathname;
      } catch {
        return url;
      }
    };
    
    const newUrlClean = cleanUrl(articleData.url);
    const isDuplicate = articles.some(article => cleanUrl(article.url) === newUrlClean);
    
    if (isDuplicate) {
      return {
        type: 'warning',
        message: '该文章已存在，请勿重复添加'
      };
    }
    
    // 生成唯一ID
    const id = Date.now().toString(36) + Math.random().toString(36).substr(2);
    
    // 创建新文章记录
    const newArticle = {
      id,
      title: articleData.title,
      author: articleData.author,
      publishTime: articleData.publishTime,
      url: articleData.url,
      addedTime: new Date().toISOString()
    };
    
    // 添加到列表开头（最新在前）
    articles.unshift(newArticle);
    
    // 保存
    await chrome.storage.local.set({ articles });
    
    return {
      type: 'success',
      message: `添加成功：${articleData.title.substring(0, 20)}${articleData.title.length > 20 ? '...' : ''}`
    };
  } catch (error) {
    console.error('保存文章失败:', error);
    return {
      type: 'error',
      message: '保存失败，请重试'
    };
  }
}

// 显示Toast提示的函数（将被注入到页面中执行）
function showToast(message, type = 'success') {
  // 移除已存在的toast
  const existingToast = document.querySelector('#wechat-collector-toast');
  if (existingToast) {
    existingToast.remove();
  }
  
  // 创建toast元素
  const toast = document.createElement('div');
  toast.id = 'wechat-collector-toast';
  
  // 设置样式
  const bgColor = {
    success: '#52c41a',
    error: '#ff4d4f',
    warning: '#faad14'
  }[type] || '#52c41a';
  
  toast.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 12px 20px;
    background: ${bgColor};
    color: white;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 500;
    z-index: 999999;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    animation: slideIn 0.3s ease;
    max-width: 300px;
    word-break: break-all;
  `;
  
  // 添加动画样式
  const style = document.createElement('style');
  style.textContent = `
    @keyframes slideIn {
      from {
        transform: translateX(100%);
        opacity: 0;
      }
      to {
        transform: translateX(0);
        opacity: 1;
      }
    }
    @keyframes slideOut {
      from {
        transform: translateX(0);
        opacity: 1;
      }
      to {
        transform: translateX(100%);
        opacity: 0;
      }
    }
  `;
  document.head.appendChild(style);
  
  toast.textContent = message;
  document.body.appendChild(toast);
  
  // 2秒后移除
  setTimeout(() => {
    toast.style.animation = 'slideOut 0.3s ease';
    setTimeout(() => {
      toast.remove();
    }, 300);
  }, 2000);
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'addArticle') {
    handleAddArticle(request.tabId).then(sendResponse);
    return true; // 保持消息通道开放
  }
});

// 处理添加文章请求
async function handleAddArticle(tabId) {
  try {
    const results = await chrome.scripting.executeScript({
      target: { tabId },
      func: extractArticleData
    });
    
    if (results && results[0] && results[0].result) {
      return await saveArticle(results[0].result);
    }
    
    return {
      type: 'error',
      message: '提取文章数据失败'
    };
  } catch (error) {
    console.error('添加文章失败:', error);
    return {
      type: 'error',
      message: '添加失败：' + error.message
    };
  }
}

